package cn.itaccount.service.impl;

import cn.itaccount.dao.accountDao;
import cn.itaccount.dao.impl.accountDaoImpl;
import cn.itaccount.domain.Account;
import cn.itaccount.service.accountService;
import cn.ittest.util.JDBCUtil;

import java.sql.Connection;
import java.sql.SQLException;

public class accountServiceImpl implements accountService {
    private accountDao dao = new accountDaoImpl();
    @Override
    public void transfer(int sid, int tid, float money) {
        Connection conn= JDBCUtil.getConnection();
        try {
            conn.setAutoCommit(false);
            Account sourceAccount = dao.findById(sid);
            Account targetAccount = dao.findById(tid);
            sourceAccount.setMoney(sourceAccount.getMoney()-money);
            targetAccount.setMoney(targetAccount.getMoney()+money);
            dao.updateAccount(conn,sourceAccount);

            //int i=1/0;
            dao.updateAccount(conn,targetAccount);
            conn.commit();
        } catch (Exception e) {
            try {
                System.out.println("操作失败！！");
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
            JDBCUtil.close(conn,null);
        }
    }
}
